package cheqex.update;

import javax.swing.*;

import java.awt.event.*;
import java.awt.print.PrinterException;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.text.MessageFormat;
import java.util.*;

import cheqex.dao.ReportPeer;
import cheqex.update.controllers.CashInBankController;
import cheqex.update.controllers.DateController;
import cheqex.update.controllers.RemarksController;

public class SummaryView extends JPanel implements ActionListener{
	private JLabel beginningBalance;
	private JLabel beginningBalanceVal;
	private JLabel totalSumOfCollections;
	private JLabel totalSumOfCollectionsVal;
	private JLabel bankInterest;
	private JLabel totalSumOfWithdrawals;
	private JLabel totalSumOfWithdrawalsVal;
	private JLabel totalCashInBankBalance;
	private JLabel totalCashInBankBalanceVal;
	
	private JTextField bankInterestField;
	
	private JButton updateBankInterest;
	private JButton previewWeeklyReport;
	
	private JPanel summaryPanel;
	private JPanel bankInterestPanel;
	
	public int weekId;
	
    private JTextArea remarks;
    private JPanel remarksPanel;
	private JButton saveRemarks;
    
	public SummaryView(){
		initialize();
	}
	
	/*	initialize
	 * 	----------
	 * 	AUTHOR: Patrisha Louisse O Sales
	 * 	initialize initializes the components of the
	 * 	SummaryView.									*/
	public void initialize(){
		weekId = CashInBankController.getCurrentWeekOfTheYear();
		
		this.summaryPanel = new JPanel();
		this.bankInterestPanel = new JPanel();
		
		this.beginningBalance = new JLabel("Beginning Balance:");
		this.beginningBalanceVal = new JLabel(Integer.toString(CashInBankController.getBeginningBalance(weekId)));
		this.totalSumOfCollections = new JLabel("Total Sum of Collections:");
		this.totalSumOfCollectionsVal = new JLabel(Integer.toString(CashInBankController.getTotalSumOfCollections(weekId)));
		this.bankInterest = new JLabel("Bank Interest:");
		this.totalSumOfWithdrawals = new JLabel("Total Sum of Withdrawals:");
		this.totalSumOfWithdrawalsVal = new JLabel(Integer.toString(CashInBankController.getTotalSumOfWithdrawals(weekId)));
		this.totalCashInBankBalance = new JLabel("Total Cash in Bank Balance:");
		this.totalCashInBankBalanceVal = new JLabel(Integer.toString(CashInBankController.getTotalCashInBankBalance(weekId)));
		
		this.bankInterestField = new JTextField(2);
		this.bankInterestField.setText(Integer.toString(CashInBankController.getBankInterest(weekId)));
		this.bankInterestField.addKeyListener(new KeyListener(){

			@Override
			public void keyPressed(KeyEvent e) {
				if(e.getKeyCode()==KeyEvent.VK_ENTER){
					updateSummary();
				}
				
			}

			@Override
			public void keyReleased(KeyEvent e) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void keyTyped(KeyEvent e) {
				// TODO Auto-generated method stub
				
			}
			
		});
		
		this.updateBankInterest = new JButton("Update");
		this.previewWeeklyReport =  new JButton("Print Weekly Report");
		
		updateBankInterest.setMnemonic(KeyEvent.VK_D);
	    updateBankInterest.setActionCommand("updateBankInterest");
	    updateBankInterest.setEnabled(true);
	    updateBankInterest.addActionListener(this);
	    
	    previewWeeklyReport.setMnemonic(KeyEvent.VK_D);
	    previewWeeklyReport.setActionCommand("previewWeeklyReport");
	    previewWeeklyReport.setEnabled(true);
	    previewWeeklyReport.addActionListener(this);
	    
	  //for remarks
	    String savedRemarks;
		if(RemarksController.getWeeklyRemarks(CashInBankController.getCurrentWeekOfTheYear())!=null){
			savedRemarks = RemarksController.getWeeklyRemarks(CashInBankController.getCurrentWeekOfTheYear());
		} else savedRemarks = null;
		
	    saveRemarks = new JButton("Save Remarks");
	    saveRemarks.setSize(5,5);
	    saveRemarks.setActionCommand("saveRemarks");
	    saveRemarks.addActionListener(this);
	    remarks = new JTextArea(savedRemarks,5,17);
	    remarks.setLineWrap(true);
	    remarksPanel = new JPanel();
	    remarksPanel.add(remarks);
	    remarksPanel.add(saveRemarks);
	    remarksPanel.setSize(10,15);
	    remarksPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
	    
	    
	    summaryPanel.setLayout(new GridLayout(7,2));
	    
	    summaryPanel.add(beginningBalance);
	    summaryPanel.add(beginningBalanceVal);
	    summaryPanel.add(totalSumOfCollections);
	    summaryPanel.add(totalSumOfCollectionsVal);
	    summaryPanel.add(bankInterestPanel);
	    bankInterestPanel.setLayout(new GridLayout(1,1));
	    bankInterestPanel.add(bankInterest);
	    bankInterestPanel.add(bankInterestField);
	    summaryPanel.add(updateBankInterest);
	    summaryPanel.add(totalSumOfWithdrawals);
	    summaryPanel.add(totalSumOfWithdrawalsVal);
	    summaryPanel.add(totalCashInBankBalance);
	    summaryPanel.add(totalCashInBankBalanceVal);
	    summaryPanel.add(previewWeeklyReport);
	    
	    this.add(summaryPanel);
	    this.add(remarksPanel);
	    this.setLayout(new GridLayout(2,0));
	    this.setVisible(true);
	}
	
	public void actionPerformed(ActionEvent e) {
		if ("updateBankInterest".equals(e.getActionCommand())) {
			updateSummary();
		}
		
		if ("previewWeeklyReport".equals(e.getActionCommand())) {
			createSummaryTable();
		}
		
		if("saveRemarks".equals(e.getActionCommand())){
			addRemarks();
		}
	}
	
	private void addRemarks(){
		try{
			if(RemarksController.getWeeklyRemarks(CashInBankController.getCurrentWeekOfTheYear())==null)
			RemarksController.addWeeklyRemarks(CashInBankController.getCurrentWeekOfTheYear(), remarks.getText());
			else RemarksController.updateWeeklyRemarks(CashInBankController.getCurrentWeekOfTheYear(), remarks.getText());
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	/*	updateSummary
	 * 	-------------
	 * 	AUTHOR: Patrisha Louisse O Sales
	 * 	updateSummary gets the bank interest entered by the user, verifies if
	 * 	the bank interest is valid and then passes on to the controller the
	 * 	bank interest and updates the total cash in bank balance for
	 * 	that week.																*/
	private void updateSummary(){
		int weekId = CashInBankController.getCurrentWeekOfTheYear();
		int bankInterest = 0;
		int amtLength = bankInterestField.getText().length();
		if(amtLength>15)
			JOptionPane.showMessageDialog(null,"Bank interest is too long.", "Error", JOptionPane.WARNING_MESSAGE);
		else if(CashInBankController.isNumeric(bankInterestField.getText())){
			bankInterest = Integer.parseInt(bankInterestField.getText());
			if(bankInterest==0)
				JOptionPane.showMessageDialog(null,"Bank interest should not be equal to zero.", "Error", JOptionPane.WARNING_MESSAGE);
		}else{ 
			JOptionPane.showMessageDialog(null,"Bank interest should only consists of digits.", "Error", JOptionPane.WARNING_MESSAGE);
		}
			
		CashInBankController.recomputeTotalCashInBankBalance(weekId, bankInterest);
		this.beginningBalanceVal.setText(Integer.toString(CashInBankController.getBeginningBalance(weekId)));
		this.totalSumOfCollectionsVal.setText(Integer.toString(CashInBankController.getTotalSumOfCollections(weekId)));
		this.bankInterestField.setText(Integer.toString(CashInBankController.getBankInterest(weekId)));
		this.totalSumOfWithdrawalsVal.setText(Integer.toString(CashInBankController.getTotalSumOfWithdrawals(weekId)));
		this.totalCashInBankBalanceVal.setText(Integer.toString(CashInBankController.getTotalCashInBankBalance(weekId)));
	}
	/*		END OF updateSummary		*/
	
	/*	createSummaryTable
	 * 	------------------
	 * 	AUTHOR: Patrisha Louisse O Sales
	 * 	createSummaryTable creates a table for the summary for the weekly report
	 * 	for printing.
	 * 	------------------
	 * 	Code from printing was patterned after:
	 * 	http://www.jguru.com/faq/view.jsp?EID=1251266
	 * 																				*/
	private void createSummaryTable(){
		final Object rows[][] = {
				{ "BEGINNING BALANCE", this.beginningBalanceVal.getText() },
				{ "TOTAL SUM OF COLLECTIONS", this.totalSumOfCollectionsVal.getText() },
				{ "BANK INTEREST", this.bankInterestField.getText() },
				{ "TOTAL SUM OF WITHDRAWALS", this.totalSumOfWithdrawalsVal.getText() },
				{ "TOTAL CASH IN BANK BALANCE", this.totalCashInBankBalanceVal.getText() },
		};
		
		final Object headers[] = {"SUMMARY", ""};
		Runnable runner = new Runnable() {
		      public void run() {
		        JFrame frame = new JFrame("Weekly Report");
		        final JTable table = new JTable(rows, headers);
		        JScrollPane scrollPane = new JScrollPane(table);
		        frame.add(scrollPane, BorderLayout.CENTER);
		        JButton button = new JButton("Print Weekly Report");
		        ActionListener printAction = new ActionListener() {
		          public void actionPerformed(ActionEvent e) {
		            try {
		              MessageFormat headerFormat = new MessageFormat("Page {0}");
		              MessageFormat footerFormat = new MessageFormat("- {0} -");
		              table.print(JTable.PrintMode.FIT_WIDTH, headerFormat, footerFormat);
		            } catch (PrinterException pe) {
		              System.err.println("Error printing: " + pe.getMessage());
		            }
		          }
		        };
		        button.addActionListener(printAction);
		        frame.add(button, BorderLayout.SOUTH);
		        frame.pack();
		        frame.setVisible(true);
		      }
		    };
		    EventQueue.invokeLater(runner);
	}
	/*		END OF createSummaryTable*/
}
